import http from "@/utils/http"
import { getLocalChannels, hasToken, setLocalChannels } from "@/utils/storage"
import store, { AppDispatch } from ".."
import { Channel, NewsTypeLast } from "../reducer/channel"

/**
 * 获取用户频道列表
 */
export const getChannels = () => {
  return async (dispatch: AppDispatch) => {
    let tempData = []
    // 1.登录的情况，返回后台的数据
    if (hasToken()) {
      const res = await http.get(`/v1_0/user/channels`)
      tempData = res.data.channels
    } else {
      //2.未登录的情况，返回默认数据
      // 2.1已经存过数据一次了，不用在发请求
      if (getLocalChannels().length) tempData = getLocalChannels()
      else {
        // 2.2还没有存过数据
        const res = await http.get(`/v1_0/user/channels`)
        setLocalChannels(res.data.channels)
        tempData = res.data.channels
      }
    }
    dispatch({ type: 'channel/saveList', payload: tempData })
  }
}

/**
 * 获取首页全部频道列表
 */
export const getAllChannels = () => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get(`/v1_0/channels`)
    dispatch({ type: 'channel/saveAllList', payload: res.data.channels })
  }
}

/**
 * 添加我的频道
 */
export const channelAdd = (item: Channel) => {
  return async (dispatch: AppDispatch) => {
    const { list } = store.getState().channel
    const newList = [...list, item]
    // 1.登录了，发请求
    if (hasToken()) await http.patch('/v1_0/user/channels', { channels: newList })
    // 2.未登录，本地存储
    else setLocalChannels(newList)
    dispatch({ type: 'channel/saveList', payload: newList })
  }
}

/**
 * 删除我的频道
 */
export const channelDel = (id: number) => {
  return async (dispatch: AppDispatch) => {
    const { list } = store.getState().channel
    const newList = list.filter(v => v.id !== id)
    // 1.登录了，发请求
    if (hasToken()) await http.delete(`/v1_0/user/channels/${id}`)
    // 2.未登录，本地存储
    else setLocalChannels(newList)
    dispatch({ type: 'channel/saveList', payload: newList })
  }
}


/**
 * 根据顶部id获取新闻列表（包含无限滚动）
 */
export const getNewList = (id: number, timestamp: number, flag: boolean) => {

  return async (dispatch: AppDispatch) => {
    const { newsList, nowTime } = store.getState().channel
    const oldList = newsList[id] || [] as NewsTypeLast

    if (flag) {
      if (newsList[id]) return
    } else {
      if (newsList[id] && !nowTime[id]) return
    }
    const res = await http.get(`/v1_0/articles?channel_id=${id}&timestamp=${timestamp}`)
    dispatch({ type: 'channel/saveNewList', payload: [...oldList, ...res.data.results] })
    dispatch({ type: 'channel/setTime', payload: Number(res.data.pre_timestamp) })
  }
}

/**
 * 下拉刷新
 */
export const refreshNewList = (id: number, timestamp = Date.now()) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get(`/v1_0/articles?channel_id=${id}&timestamp=${timestamp}`)
    dispatch({ type: 'channel/saveNewList', payload: res.data.results })
  }
}